using Microsoft.EntityFrameworkCore;

namespace EFCoreTableSplitDemo;

public class TableSplittingContext : DbContext
{
    public TableSplittingContext(DbContextOptions<TableSplittingContext> options) : base(options)
    {

    }

    public DbSet<Order> Orders { get; set; }
    public DbSet<Product> Products { get; set; }
    public DbSet<OrderItem> OrderItems { get; set; }
    public DbSet<ProductAttribute> ProductAttributes { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Order>().ToTable("Orders").HasKey(o => o.Id);
        modelBuilder.Entity<Order>().Property(t => t.Id).ValueGeneratedOnAdd();
        modelBuilder.Entity<Order>().HasMany(o => o.OrderItems);

        modelBuilder.Entity<Product>().ToTable("Products").HasKey(o => o.Id);
        modelBuilder.Entity<Product>().Property(t => t.Id).ValueGeneratedOnAdd();

        modelBuilder.Entity<OrderItem>().ToTable("OrderItems").HasKey(o => o.Id);
        modelBuilder.Entity<OrderItem>().Property(t => t.Id).ValueGeneratedOnAdd();
        modelBuilder.Entity<OrderItem>().HasOne(o => o.Product).WithMany().HasForeignKey(t => t.ProductId);
        modelBuilder.Entity<OrderItem>().HasOne(o => o.ProductAttribute).WithOne().HasForeignKey<ProductAttribute>(t => t.Id);
        modelBuilder.Entity<OrderItem>().Property(t => t.ProductId).HasColumnName("ProductId");

        modelBuilder.Entity<ProductAttribute>().ToTable("OrderItems").HasKey(o => o.Id);
        //modelBuilder.Entity<ProductAttribute>().Property(t => t.ProductId).HasColumnName("ProductId");

        base.OnModelCreating(modelBuilder);
    }
}